package package2;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

public class AnimalAnnotationProcessor {

    public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        operationAnnotation(Dog.class);
    }

    private static void operationAnnotation(Class<?> clazz) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        // 获取类上的私有字段
        Field[] fields = clazz.getDeclaredFields();
        StringBuffer stringBuffer = new StringBuffer();
        Arrays.stream(fields).forEach(p ->{
            AnimalAnnotation annotation = p.getAnnotation(AnimalAnnotation.class);
            if(annotation.value().length() > 0){
                stringBuffer.append("我家小狗叫："+annotation.value());
            }
            if(annotation.hairColor().length()>0){
                stringBuffer.append("\n它的毛发是："+annotation.hairColor());
            }
            if(annotation.id() > 0){
                stringBuffer.append("\n编号为："+annotation.id());
            }
        });

        // 获取方法
        Method method = clazz.getDeclaredMethod("getDog", String.class);
        // 获取方法上的注解
        AnimalAnnotation annotation = method.getAnnotation(AnimalAnnotation.class);
        if(annotation.invoke()){
            // 执行getDog方法
            method.invoke(clazz.newInstance(),stringBuffer.toString());
        }
    }
}
